<template>
  <a-card>
    <a-form :form="form" @submit="handleSubmit" :labelCol="formItemLayout.labelCol"
      :wrapperCol="formItemLayout.wrapperCol">
      <a-form-item label="门店包名称">
        <a-input placeholder="请输入门店包名称" :maxLength="20" v-decorator="[
          `storePackageName`,
          {
            rules: [
              {
                required: true,
                whitespace: true,
                message: '请输入门店包名称',
              },
            ],
          },
        ]"></a-input>
      </a-form-item>
      <a-form-item label="添加方式">
        <a-radio-group v-decorator="[
          `type`,
          { initialValue: 0, rules: [{ required: true, message: '请选择添加方式' }] },
        ]" @change="onChange">
          <a-radio :value="0">条件筛选</a-radio>
          <a-radio :value="1">导入</a-radio>
        </a-radio-group>
      </a-form-item>
      <div v-if="!importType">
        <a-form-item label="品牌架构">
          <JSelect :options="brands" placeholder="请选择品牌架构" v-decorator="[`storePackageBrand`]"></JSelect>
        </a-form-item>
        <a-form-item label="所属经销商">
          <JSelect :options="distributor" placeholder="请选择经销商" v-decorator="[`saveCustomerDTOList`]">
          </JSelect>
        </a-form-item>
        <a-form-item label="省市区">
          <JTreeSelect placeholder="请选择省市区" v-decorator="[`address`]"></JTreeSelect>
        </a-form-item>
        <a-form-item label="销售区域">
          <JSelect :options="area" placeholder="请选择销售区域" v-decorator="[`saveAreaDTOList`]"></JSelect>
        </a-form-item>
        <a-form-item label="是否奥莱">
          <!-- {initialValue:1} -->
          <a-radio-group v-decorator="[`isOulet`]">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="区部">
          <a-select v-decorator="[`storeMinistry`]" style="width: 180px" placeholder="请选择区部">
            <a-select-option value="直营">直营</a-select-option>
            <a-select-option value="经销">经销</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否特卖">
          <a-select v-decorator="[
            `isTm`,
            {
              initialValue: 0,
              rules: [
                {
                  required: true,
                  message: '请选择是否特卖',
                },
              ],
            },
          ]" style="width: 180px" placeholder="请选择是否特卖">
            <a-select-option :value="2">全部</a-select-option>
            <a-select-option :value="1">是</a-select-option>
            <a-select-option :value="0">否</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否包含集合店子店 ">
          <!-- {initialValue:1} -->
          <a-radio-group v-decorator="[`unionStoreId`]">
            <a-radio value="0">是</a-radio>
            <a-radio value="1">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
      <div v-else>
        <a-form-item :wrapperCol="offset">
          <TableFormItem v-decorator="[
            `storeGroupCode`,
            { rules: [{ required: true, message: '请上传门店' }] },
          ]" />
        </a-form-item>
      </div>
      <a-form-item :wrapperCol="offset">
        <div>*门店包常用配置方式参考 <a-button type="link" @click="linkHandle">查看</a-button></div>
      </a-form-item>
      <a-form-item :wrapperCol="offset">
        <a-button :loading="loading" type="primary" html-type="submit">保存</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import JSelect from "../components/JSelect.vue";
import JTreeSelect from "../components/jTreeSelect.vue";
import TableFormItem from "../components/TableFormItem.vue";
// import { brands } from '../../micromall/util/brand'
import {
  queryCustomer,
  queryStoreArea,
  storePackage,
  storePackageDetail,
  queryBrand,
} from "@/api/micromall/storePackage";
export default {
  name: "",
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xl: { span: 8 },
          xs: { span: 12 },
          sm: { span: 12 },
        },
      },
      offset: {
        xl: { span: 14, offset: 5 },
        xs: { span: 12, offset: 5 },
        sm: { span: 12, offset: 6 },
      },
      importType: false,
      brands: [],
      distributor: [],
      area: [],
      loading: false,
    };
  },
  components: {
    JSelect,
    JTreeSelect,
    TableFormItem,
  },
  created() {
    this.getCustomer();
    this.getArea();
    this.getBrand();
  },
  mounted() {
    const { id, isCopy } = this.$route.query;
    if (id) {
      this.getInfo(id);
      this.id = id;
      this.isCopy = isCopy;
    }
  },
  methods: {
    linkHandle() {
      window.open('https://alidocs.dingtalk.com/i/nodes/lDZEN6or0dp8Zx3ArezlVaPYQK91xzy3?cid=23229950%3A545935397&iframeQuery=sheet_range%3Dkgqie6hm_15_0_1_1%26utm_medium%3Dim_card%26utm_source%3Dim&utm_medium=im_single_card&utm_source=im&utm_scene=person_space&dontjump=true&corpId=ding8bac6beff1d2d841')
    },
    async getInfo(id) {
      const res = await storePackageDetail(id);
      if (res.code == 200) {
        const { storePackageName, type } = res.data;
        const values = {
          storePackageName,
          type: type ? parseInt(type) : 0,
        };
        this.importType = type == 1;
        // 条件筛选
        if (type == 0) {
          const {
            provincesIsThe,
            customerIsThe,
            areaIsThe,
            brandIsThe,
            storePackageBrand,
            storeMinistry,
            isOulet,
            saveAreaDTOList,
            saveCustomerDTOList,
            saveProvincesDTOList,
            isTm,
            unionStoreId
          } = res.data;
          values.isTm = Number(isTm)
          values.unionStoreId = unionStoreId

          // 品牌筛选
          if (storePackageBrand != "") {
            values.storePackageBrand = {
              selectValue: storePackageBrand.split(",").map((item) => Number(item)),
              selectType: Number(brandIsThe),
            };
          }
          if (saveAreaDTOList.length > 0) {
            values.saveAreaDTOList = {
              selectValue: saveAreaDTOList.map((item) => Number(item.areaId)),
              selectType: Number(areaIsThe),
            };
          }
          if (saveCustomerDTOList.length > 0) {
            values.saveCustomerDTOList = {
              selectValue: saveCustomerDTOList.map((item) => Number(item.customerId)),
              selectType: Number(customerIsThe),
            };
          }
          if (saveProvincesDTOList) {
            console.log(saveProvincesDTOList);
            values.address = {
              selectType: Number(provincesIsThe),
              selectValue: saveProvincesDTOList.map((item) => {
                console.log(item);
                const { provinceId, cityId, districtId } = item;
                return districtId
                  ? `${provinceId}-${cityId}-${districtId}`
                  : cityId
                    ? `${provinceId}-${cityId}`
                    : provinceId;
              }),
            };
          }
          if (isOulet != "") {
            values.isOulet = Number(isOulet);
          }
          if (storeMinistry != "") {
            values.storeMinistry = storeMinistry;
          }
        } else {
          const { storeGroupCode } = res.data;
          values.storeGroupCode = storeGroupCode;
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(values);
          console.log(values);
        });
      }
      console.log(res);
    },
    async getBrand() {
      const { code, data, message, msg } = (await queryBrand()) || {};
      if (code == 200) {
        this.brands = data;
      } else {
        this.$message.error(msg || message);
      }
    },
    async getCustomer() {
      const res = await queryCustomer();
      this.distributor = res.data;
      console.log("getCustomer", res);
    },
    async getArea() {
      const res = await queryStoreArea();
      this.area = res.data;
      console.log("getArea", res);
    },

    onChange(e) {
      this.importType = e.target.value == 1;
    },
    isSelect(value) {
      return value && value.selectValue != undefined;
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        console.log(err, values);
        if (!err) {
          const {
            address,
            saveCustomerDTOList,
            storeMinistry,
            storePackageBrand,
            isOulet,
            saveAreaDTOList,
            type,
          } = values;
          console.log(values, isOulet == 0 || isOulet == 1);
          if (
            !this.isSelect(address) &&
            !this.isSelect(saveAreaDTOList) &&
            !this.isSelect(saveCustomerDTOList) &&
            !this.isSelect(storePackageBrand) &&
            !(isOulet == 0 || isOulet == 1) &&
            !storeMinistry &&
            type == 0
          ) {
            return this.$message.error("请至少选择一项筛选条件");
          }
          this.submit(values);
        }
      });
    },
    async submit(values) {
      this.loading = true;
      let { storePackageName, type } = values;
      const { distributor, area, id, isCopy } = this;
      let params = { storePackageName, type };
      // 复制操作
      if (!isCopy && id) {
        params.id = id;
      }
      if (type == 0) {
        let {
          address,
          saveAreaDTOList,
          saveCustomerDTOList,
          storePackageBrand,
          isOulet,
          storeMinistry,
          isTm,
          unionStoreId
        } = values;
        params = Object.assign(params,{isOulet, storeMinistry, isTm, unionStoreId})
        let { selectValue: areaIds, selectType: areaIsThe } = saveAreaDTOList || {};
        if (areaIds) {
          params.saveAreaDTOList = this.filterArr(area, areaIds, "areaId", "areaName");
          params.areaIsThe = areaIsThe;
        }
        let { selectValue: customerIds, selectType: customerIsThe } =
          saveCustomerDTOList || {};
        if (customerIds) {
          params.saveCustomerDTOList = this.filterArr(
            distributor,
            customerIds,
            "customerId",
            "customerName"
          );
          params.customerIsThe = customerIsThe;
        }
        let { selectValue: brandIds, selectType: brandIsThe } = storePackageBrand || {};
        if (brandIds) {
          params.storePackageBrand = brandIds.join();
          params.brandIsThe = brandIsThe;
        }
        const { selectValue: addressInfo, selectType: provincesIsThe } = address || {};
        if (addressInfo) {
          console.log(addressInfo);
          const addressList = addressInfo.map((item) => {
            const [provinceId, cityId, districtId] = String(item).split("-");
            return { provinceId, cityId, districtId };
          });
          params.provincesIsThe = provincesIsThe;
          params.saveProvincesDTOList = addressList;
        }
      } else {
        params.storeGroupCode = values.storeGroupCode;
      }
      console.log(params);
      const res = await storePackage(params);
      this.loading = false;
      if (res.code == 200) {
        this.$message.success("保存成功");
        this.$router.back();
      } else {
        this.$message.error(res.msg || res.message);
      }
    },
    filterArr(arr, ids, idKey, nameKey) {
      return arr
        .filter((item) => ids.includes(item.id))
        .map((item) => {
          const obj = {};
          obj[idKey] = item.id;
          obj[nameKey] = item.name;
          return obj;
        });
    },
  },
};
</script>

<style scoped>

</style>
